﻿using System;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace IOP.Extension.Json
{
    /// <summary>
    /// 多枚举值Json转换器
    /// </summary>
    public class JsonStringEnumArrayConverter : JsonConverterFactory
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public JsonStringEnumArrayConverter() { }
        /// <summary>
        /// 是否允许转换
        /// </summary>
        /// <param name="typeToConvert"></param>
        /// <returns></returns>
        public override bool CanConvert(Type typeToConvert)
        {
            if (typeToConvert.IsArray)
            {
                string tName = typeToConvert.FullName.Replace("[]", string.Empty);
                Type oType = typeToConvert.Assembly.GetType(tName);
                return oType.IsEnum;
            }
            return typeToConvert.IsEnum;
        }
        /// <summary>
        /// 创建转换器
        /// </summary>
        /// <param name="typeToConvert"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            JsonConverter converter = (JsonConverter)Activator.CreateInstance(
                typeof(JsonConverterEnumArray<>).MakeGenericType(typeToConvert),
                BindingFlags.Instance | BindingFlags.Public,
                binder: null,
                args: null,
                culture: null);

            return converter;
        }
    }
}
